package com.gupao.edu.homework.chatroom;

import com.gupao.edu.utils.CloseUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @description：服务端处理器
 * @author：GP16803-林华滨
 * @version：2018年11月01日 15:19
 */
public class ServerHandler implements Runnable {

    /***
     * 输入流
     */
    private BufferedReader in;
    /***
     * 输出流
     */
    private PrintWriter out;
    /***
     * 客户端名称
     */
    private String member;
    /***
     * 所有的客户端
     */
    private List<ServerHandler> chatRoomMembers;
    /***
     * 线程运行标识
     */
    private boolean isRunning = Boolean.TRUE;

    public ServerHandler(Socket socket, List<ServerHandler> chatRoomMembers) {
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream());
            // 保存当天的聊天对象
            this.member = in.readLine();
            this.send(String.format("欢迎您（{0}）进入聊天室", this.member));
            this.sendOther(this.member + "进入聊天室");
        } catch (IOException e) {
            e.printStackTrace();
            this.isRunning = false;
            CloseUtil.clearResources(this.in, this.out);
        }
        this.chatRoomMembers = chatRoomMembers;
    }

    @Override
    public void run() {
        while (isRunning) {
            String msg = this.receive();
            this.sendOther(msg);
        }
    }

    /***
     * 接收信息
     * @return
     */
    private String receive() {
        String msg = "";
        try {
            // 从成员的输入流中读取信息
            msg = in.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            this.isRunning = false;
            CloseUtil.clearResources(this.in, this.out);
            chatRoomMembers.remove(this);
            System.out.println("读取成员的输入信息报错：" + e.getLocalizedMessage());
        }
        return msg;
    }

    /***
     * 发送信息
     * @param data
     */
    private void send(String data) {
        if (null != data && !"".equals(data)) {
            out.println(data);
            out.flush();
        }
    }

    /***
     * 发送本次成员输入信息给其他成员
     * @param data
     */
    private void sendOther(String data) {
        // ServerHandler 创建的时候 chatRoomMembers 为 NULL，导致问题：java.net.SocketException: Connection reset
        if (null == chatRoomMembers) {
            chatRoomMembers = new ArrayList<>(0);
        }

        for (ServerHandler other : chatRoomMembers) {
            // 排除自已
            if (this == other) {
                continue;
            }

            // 发送信息
            other.send(this.member + " --> " + other.member + "：" + data);
        }
    }
}
